{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2e4bf996",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n",
      "[20 30 40]\n"
     ]
    }
   ],
   "source": [
    "# 一维数组索引与切片\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "arr = np.array([10, 20, 30, 40, 50])\n",
    "\n",
    "# 使用索引访问单个元素\n",
    "print(arr[0])\n",
    "\n",
    "# 使用切片获取子数组\n",
    "print(arr[1:4])  # 包括索引1到3的元素\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "0ef87d0b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6\n",
      "[[2 3]\n",
      " [5 6]]\n"
     ]
    }
   ],
   "source": [
    "# 多维数组索引与切片\n",
    "# NumPy 支持对多维数组进行索引与切片。在多维数组中，索引是通过元组来表示的，每个维度使用一个索引。\n",
    "\n",
    "arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n",
    "# 索引单个元素\n",
    "print(arr2d[1, 2])  # 第二行第三列的元素\n",
    "\n",
    "# 切片行和列\n",
    "print(arr2d[0:2,1:3])  # 第一行和第二行的第二列"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "3337565a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[3 4 5]\n",
      "[3 4 5]\n"
     ]
    }
   ],
   "source": [
    "# 3. 布尔索引与条件索引\n",
    "# 布尔索引是根据条件生成布尔值数组来筛选数组中的元素。这非常适合进行条件过滤和选择。\n",
    "\n",
    "arr = np.array([1, 2, 3, 4, 5])\n",
    "\n",
    "# 创建一个布尔索引条件\n",
    "condition = arr > 2\n",
    "\n",
    "# 使用布尔索引筛选数组\n",
    "filtered_arr = arr[condition]\n",
    "print(filtered_arr)  # 输出大于2的元素\n",
    "\n",
    "# 直接在数组上使用条件\n",
    "print(arr[arr>2])  # 输出大于2的元素\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "6fcd8d0f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[10 30 50]\n",
      "[2 9]\n"
     ]
    }
   ],
   "source": [
    "# 4. 花式索引（Fancy Indexing）\n",
    "# 花式索引指的是使用整数数组或列表来选择数组的多个元素。它可以用于选择数组中的特定元素（而不是连续的子数组）。\n",
    "\n",
    "arr = np.array([10, 20, 30, 40, 50])\n",
    "\n",
    "# 使用整数数组作为索引\n",
    "indices = [0,2,4]\n",
    "print(arr[indices])\n",
    "\n",
    "# 在多维数组中，花式索引也可以应用于不同维度。\n",
    "arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n",
    "# 使用花式索引选择特定行\n",
    "print(arr2d[[0, 2], [1, 2]])  # 输出 [2 9]"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
